from urllib.parse import unquote
import App_setting as setting
import falcon

from WebBackend.dataclass.Directory import __path_is_allow__
from WebBackend.interface.management.Directory.dir_list import list_directory_contents
from WebBackend.middleware.virtualWorldGate_Chuche import login_require


@falcon.before(login_require)
class DirectoryAPI:
    def __init__(self, ):
        pass

    async def on_get(self, req: falcon.Request, resp: falcon.Response):
        path = req.params.get('p')
        path = unquote(path)
        if path == '':
            path = setting.security.allow_directory_browse[0]
        if path != "" and not __path_is_allow__(path):
            raise falcon.HTTPNotAcceptable(title='invalid path')

        resp.media = await list_directory_contents(path)

